package com.victualler.core.common.enums;

import com.victualler.core.common.dto.DictItemVO;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @Aouthor Guoshichang
 * @Date 11:23 on 2018/6/12.
 * @Function 注解加载器 负责将注解信息加载到此容器中
 */
@Component
public class EnumsManager {
    private Map<String,List<DictItemVO>> enumsClassMap; //根据枚举的全类名获取注解信息
    private Map<String,List<DictItemVO>> perpotiesEnumsMap;  //根据注解的

    public EnumsManager(){
        enumsClassMap = new HashMap<>();
        perpotiesEnumsMap = new HashMap<>();
        //加载资源文件
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("enumsRegister.yml"));
        Properties properties = yaml.getObject();
        try {
            //加载对应枚举的资源文件
            this.loadDatas(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @Aouthor Guoshichang
     * @Date 12:33 on 2018/6/12.
     * @param properties 配置文件
     * @Function 从配置文件中加载枚举属性到map中
     */

    private void loadDatas(Properties properties) throws Exception{
        for (String key : properties.stringPropertyNames()) {
            String className = properties.getProperty(key);
            Class enumsClass= Class.forName(className);

            Object[] enums = enumsClass.getEnumConstants();
            List<DictItemVO> enumList = new ArrayList<>();
            for (Object anEnum : enums) {

                Field keyField = anEnum.getClass().getDeclaredField("key");
                keyField.setAccessible(true);
                Field valueField = anEnum.getClass().getDeclaredField("value");
                valueField.setAccessible(true);
                //取枚举的key value 属性
                String enumKey =   (String)keyField.get(anEnum);
                String enumValue =   (String)valueField.get(anEnum);
                //加入map
                enumList.add(new DictItemVO(enumKey,enumValue));
            }
            enumsClassMap.put(className,enumList);
            perpotiesEnumsMap.put(key,enumList);
            System.err.println("[EnumsManager]:"+className+" Enum is added");
        }
    }


    /**
     * @Aouthor Guoshichang
     * @Date 12:40 on 2018/6/12.
     * @param propertiesKey
     * @Function 根据配置文件配置的key 获取对应的枚举键值对
     */
    public List<DictItemVO> getValues(String propertiesKey){
        return this.perpotiesEnumsMap.get(propertiesKey);
    }

    /**
     * @Aouthor Guoshichang
     * @Date 12:40 on 2018/6/12.
     * @param enums 某个注册的枚举对象
     * @Function  根据枚举对象 获取对应的键值对
     */

    public List<DictItemVO> getValues(Enum enums){
        return this.enumsClassMap.get(enums.getClass().getName());
    }


}
